package com.dabai.linktools;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;
import com.dabai.linktools.databinding.ActivityBiliDownloadBinding;
import com.dabai.linktools.utils.Patterns;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;

public class BiliDownloadActivity extends AppCompatActivity {

    ActivityBiliDownloadBinding abdb;
    private String link;
    String TAG = "dabaizzz";
    private String BV, name;
    private String url;
    private String downfilepath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        abdb = ActivityBiliDownloadBinding.inflate(LayoutInflater.from(this));
        setContentView(abdb.getRoot());

        init();
    }


    private void init() {
        Intent intent = getIntent();
        try {

            if (intent == null)
                return;
            Bundle extras = intent.getExtras();

            if (extras == null)
                return;

            switch (intent.getType()) {
                case "text/plain"://分享的内容类型，如果png图片：image/png

                    link = "" + extras.get(Intent.EXTRA_TEXT);

                    if (!link.contains("www.bilibili.com/video/")) {
                        Toast.makeText(this, "非法请求!", Toast.LENGTH_SHORT).show();
                        finish();
                        return;
                    }

                    name = link.substring(0, link.indexOf("UP主")).replace("/", "");

                    Matcher matcher = Patterns.WEB_URL.matcher(link);
                    if (matcher.find()) {
                        link = matcher.group();
                    }


                    new Thread(() -> {

                        downfilepath = new File(getExternalFilesDir("bili_down"), name + ".mp4").getAbsolutePath();

                        BV = link.substring(link.indexOf("video/") + 6, link.lastIndexOf("?"));

                        String toapiurl = "https://api.kaaass.net/biliapi/video/resolve?bid=" + BV;

                        url = getDownUrl(toapiurl);

                        runOnUiThread(() -> {
                            toDowndown(url, downfilepath);
                        });

                    }).start();


                    break;
                default:
                    break;
            }

        } catch (Exception e) {
            Toast.makeText(this, "异常:" + e, Toast.LENGTH_LONG).show();
            finish();
            return;
        }
    }


    /**
     * 投递 链接和名字到下载类
     *
     * @param downlink
     * @param downfile
     */
    public void toDowndown(String downlink, String downfile) {

        Intent intent = new Intent(this, DownloadActivity.class);
        intent.putExtra("downlink", downlink);
        intent.putExtra("downfile", downfile);
        startActivity(intent);
        finish();
    }


    String downurl;

    /**
     * 获取 bili 下载链接
     *
     * @param url
     * @return
     */
    private String getDownUrl(String url) {
        Map<String, String> headerMap = new HashMap();
        headerMap.put("Accept", "*/*");
        headerMap.put("User-Agent", "Bilibili Freedoooooom/MarkII");

        Document doc = null;
        try {
            doc = Jsoup.connect(url).headers(headerMap).ignoreContentType(true).get();
        } catch (IOException e) {
            return "null";
        }

        JSONObject jo = JSONObject.parseObject(doc.body().text());
        jo = (JSONObject) jo.getJSONArray("url").get(0);

        downurl = jo.getString("url");

        return downurl;
    }

}
